'use strict';
let code1 = '1008' // 管理员--男友
let code2 = '0408' // 女友

let register = async (event, context, db) => {
	console.log(event.params, '接口参数')
	let {
		phone,
		code,
		username
	} = event.params
	if (!phone || !code) {
		return {
			status: false,
			message: '参数不存在'
		}
	}
	if (code !== code1 && code !== code2) {
		return {
			status: false,
			message: 'code无效'
		}
	}

	// 查询数据库，是否存在已注册身份
	let res = await db.collection('users').get();
	if (res.data.length == 0 || !res.data.find(item => item.code == code)) {
		console.log('没有')
		if (code === code1) {
			// 创建男友和管理员身份

		}
		if (code === code2) {
			// 创建女友身份
			let res2 = await db.collection("users").add({
				code: code,
				headerImage: "",
				id: 2,
				intro: "",
				phone: phone,
				username: username,
			})
			if (res2 && res2.id) {
				return {
					status: true,
					message: "注册成功"
				}
			}
		}

		return {
			status: false,
			message: "失败"
		}

	} else {
		return {
			status: false,
			message: 'code已注册'
		}
	}



}
let login = async (event, context, db) => {
	console.log(event.params, '接口参数')
	let {
		phone,
		code
	} = event.params
	if (!phone || !code) {
		return {
			status: false,
			message: '参数不存在'
		}
	}


	// 查询数据库，是否存在已注册身份
	let res = await db.collection('users').get();
	if (res.data.length == 0 || !res.data.find(item => item.phone == phone&&item.code==code)) {
		return {
			status: false,
			message: '账号不存在'
		}
	}
	console.log('存在')
	// 生成token
	let tokenJson={
		startTime:new Date().getTime(),
		effTime:60*60*24*30, // 保持时间1个月
		code,
		phone,
	}
	let token=  btoa(tokenJson);
	return {
		status: true,
		token:token,
		message: '登录成功'
	}

}
let checkCode = () => {

}
exports.main = async (event, context) => {
	//event为客户端上传的参数
	let c = event.a + event.b
	console.log(event, '接口')

	if (!event.apiName) {
		return {
			status: false,
			message: 'apiName不存在'
		}
	}
	const db = uniCloud.database();

	if (event.apiName === 'register') {
		let res = await register(event, context, db)
		return res
	}
	if (event.apiName === 'login') {
		let res = await login(event, context, db)
		return res
	}
	return {
		status: false,
		message: ""
	}
}